<template>
  <div class="tree-main-body">
    <!-- 左侧角色树 -->
    <div class="left-box">
      <TreeAdminroles
        :selected="roleIds"
        :refresh="refresh"
        :roleDelSuccess="roleDelSuccess"
        text="管理员"
        @update="handleAdminrolesUpdate"
      />
    </div>

    <!-- 右侧 -->
    <div class="right-box">
      <div class="playedu-main-title float-left mb-24">
        {{ selLabel }}
      </div>

      <!-- 顶部按钮和搜索框 -->
      <div class="float-left j-b-flex mb-24">
        <div class="d-flex">
          <PerButton
            type="primary"
            text="添加管理员"
            class="mr-16"
            :icon="h(PlusOutlined)"
            p="admin-user-cud"
            @click="createVisible = true"
          />
          <PerButton
            v-if="roleIds.length === 0"
            text="新建角色"
            class="mr-16"
            type="default"
            p="admin-role"
            @click="createRoleVisible = true"
          />
          <template v-if="!isSuper && roleIds.length > 0">
            <PerButton
              text="角色权限"
              class="mr-16"
              type="default"
              p="admin-role"
              @click="updateRoleVisible = true"
            />
            <PerButton
              text="删除角色"
              class="mr-16"
              type="default"
              p="admin-role"
              @click="delAdminRole"
            />
          </template>
        </div>

        <!-- 搜索条件 -->
        <div class="d-flex">
          <div class="d-flex mr-24">
            <Typography.Text>管理员姓名：</Typography.Text>
            <a-input
              v-model:value="name"
              style="width: 160px"
              placeholder="请输入管理员姓名"
              allowClear
            />
          </div>
          <div class="d-flex">
            <a-button class="mr-16" @click="resetData">重置</a-button>
            <a-button type="primary" @click="queryData">查询</a-button>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :dataSource="list"
        :loading="loading"
        :pagination="paginationProps"
        rowKey="id"
      />

      <!-- 弹窗：新建管理员 -->
      <SystemAdministratorCreate
        :open="createVisible"
        :roleId="roleIds[0]"
        @cancel="() => { createVisible = false; toggleRefresh(); }"
      />
      <!-- 弹窗：编辑管理员 -->
      <SystemAdministratorUpdate
        :id="cid"
        :open="updateVisible"
        @cancel="() => { updateVisible = false; toggleRefresh(); }"
      />
      <!-- 弹窗：新建角色 -->
      <SystemAdminrolesCreate
        :open="createRoleVisible"
        @cancel="() => { createRoleVisible = false; toggleRefresh(); }"
      />
      <!-- 弹窗：编辑角色 -->
      <SystemAdminrolesUpdate
        :id="roleIds[0]"
        :open="updateRoleVisible"
        @cancel="() => { updateRoleVisible = false; toggleRefresh(); }"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, h } from "vue";
import { useRoute } from "vue-router";
import {
  Typography,
  Input as AInput,
  Button as AButton,
  Table as ATable,
  Modal,
  message,
  Space,
} from "ant-design-vue";
import {
  PlusOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons-vue";
import { adminUser, adminRole } from "@/api";
import { dateFormat } from "@/utils";
import TreeAdminroles from "@/components/Common/tree-adminroles.vue";
import PerButton from "@/components/Common/permission-button.vue";
import SystemAdministratorCreate from "./create.vue";
import SystemAdministratorUpdate from "./upload.vue";
import SystemAdminrolesCreate from "../adminroles/create.vue";
import SystemAdminrolesUpdate from "../adminroles/update.vue";

const route = useRoute();

const page = ref(Number(route.query.page) || 1);
const size = ref(Number(route.query.size) || 10);
const name = ref(route.query.name as string || "");

const loading = ref(false);
const list = ref<any[]>([]);
const roles = ref<Record<string, any[]>>({});
const userRoleIds = ref<Record<number, number[]>>({});
const total = ref(0);
const refresh = ref(false);
const createVisible = ref(false);
const updateVisible = ref(false);
const createRoleVisible = ref(false);
const updateRoleVisible = ref(false);
const cid = ref(0);
const roleIds = ref<number[]>([]);
const selLabel = ref((route.query.label as string) || "全部管理员");
const roleDelSuccess = ref(false);
const isSuper = ref(false);

// 刷新列表
function toggleRefresh() {
  refresh.value = !refresh.value;
}

// 获取数据
async function getData() {
  if (loading.value) return;
  loading.value = true;
  try {
    const res: any = await adminUser.adminUserList(
      page.value, 
      size.value, 
      name.value, 
      roleIds.value[0] || undefined
    );
    list.value = res.data.data;
    roles.value = res.data.roles;
    userRoleIds.value = res.data.user_role_ids;
    total.value = res.data.total;
  } finally {
    loading.value = false;
  }
}

watch([refresh, page, size, roleIds], getData, { immediate: true });

// 表格列
const columns = [
  {
    title: "管理员",
    dataIndex: "name",
    render: ({text}: any) => h("span", text),
  },
  {
    title: "角色",
    dataIndex: "id",
    customRender: ({ record }: any) => {
      const id = record.id;
      if (!userRoleIds.value[id]) return "";
      return userRoleIds.value[id].map((item: number, index: number) => {
        const role = roles.value[item]?.[0];
        return role 
          ? (index === userRoleIds.value[id].length - 1 
              ? role.name 
              : role.name + "、")
          : "";
      });
    },
  },
  {
    title: "登录邮箱",
    dataIndex: "email",
  },
  {
    title: "登录IP",
    dataIndex: "login_ip",
    render: ({text}: any) => h("span", text),
  },
  {
    title: "上次登录时间",
    dataIndex: "login_at",
    customRender: ({ text }: any) => h("span", text && dateFormat(text)),
  },
  {
    title: "禁止登录",
    dataIndex: "is_ban_login",
    customRender: ({ text }: any) => 
      h("span", text === 0 ? "否" : "是"),
  },
  {
    title: "操作",
    key: "action",
    width: 160,
    customRender: ({ record }: any) => {
      return h(Space, { size: "small" }, [
        h(PerButton, {
          type: "link",
          text: "编辑",
          class: "b-link c-red",
          p: "admin-user-cud",
          onClick: () => {
            cid.value = record.id;
            updateVisible.value = true;
          },
        }),
        h(PerButton, {
          type: "link",
          text: "删除",
          class: "b-link c-red",
          p: "admin-user-cud",
          onClick: () => delUser(record.id),
        }),
      ]);
    },
  }
];

// 分页配置
const paginationProps = reactive({
  current: page,
  pageSize: size,
  total,
  showSizeChanger: true,
  onChange: (p: number, ps: number) => {
    page.value = p;
    size.value = ps;
  },
});

// 删除用户
function delUser(id: number) {
  if (id === 0) return;
  Modal.confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "确认删除此人员？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    async onOk() {
      await adminUser.destroyAdminUser(id);
      message.success("操作成功");
      toggleRefresh();
    },
  });
}

// 删除角色
function delAdminRole() {
  if (roleIds.value.length === 0) return;
  Modal.confirm({
    title: "操作确认",
    icon: h(ExclamationCircleFilled),
    content: "删除此角色会同时删除管理员对应关联权限，确认删除？",
    centered: true,
    okText: "确认",
    cancelText: "取消",
    async onOk() {
      await adminRole.destroyAdminRole(roleIds.value[0]);
      message.success("操作成功");
      toggleRefresh();
      roleDelSuccess.value = !roleDelSuccess.value;
    },
  });
}

// 角色树选择
function handleAdminrolesUpdate(keys: number[], title: string, isSuperRole: boolean) {
  page.value = 1;
  roleIds.value = keys;
  isSuper.value = isSuperRole;
  const index = title.indexOf("(");
  selLabel.value = index !== -1 ? title.substring(0, index) : title;
}

// 搜索重置
function resetData() {
  page.value = 1;
  size.value = 10;
  name.value = "";
  list.value = [];
  toggleRefresh();
}

// 查询
function queryData() {
  page.value = 1;
  toggleRefresh();
}
</script>

<style scoped>

</style>